import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { WingBlank, WhiteSpace, InputItem, Button, Checkbox, Toast } from 'antd-mobile'
import {
    userReg
} from '../../apis/login'

export default class Register extends Component {

    constructor() {
        super()
        this.state = {
            isAgree: false,        // 是否同意开通协议
            userPhone: '',         // 用户登录手机号
            userName: '',          // 用户姓名
        }
    }

    phoneChange = val => {
        this.setState({
            userPhone: val
        })
    }

    nameChange = val => {
        this.setState({
            userName: val
        })
    }

    // checkbox 组件返回的数据是一个事件
    agreeChange = evt => {
        this.setState({
            isAgree: evt.target.checked
        })
    }

    // 提交事件
    submitEvt = async () => {
        // TODO 对数据进行校验 /^1[0-9]{10}/ /^1[1-9]{1}[0-9]{9}/ /^(131)|(130)[0-9]{8}/

        Toast.loading('注册中...')
        let result = await userReg(this.state.userPhone.replace(/\s/g, ''), this.state.userName)
        Toast.hide()
        if (result.code === 200) {
            Toast.success('注册成功，请重新登录')
            this.props.history.push('/login', result)
        } else {
            // Toast.fail('注册失败，原因：' + result.message)
            Toast.fail(result.message || '注册失败')
        }
    }

    render() {
        return (
            <WingBlank>

                <WhiteSpace size="lg"/>
                <p>用户注册</p>
                <WhiteSpace size="lg"/>
                <InputItem type="phone" onChange={this.phoneChange}>手机号</InputItem>
                <WhiteSpace size="lg"/>
                <InputItem onChange={this.nameChange}>用户名</InputItem>
                <WhiteSpace size="lg"/>
                <Checkbox.AgreeItem onChange={this.agreeChange}>是否同意</Checkbox.AgreeItem>
                <Link to="/agreement">《XXX注册服务协议》</Link>
                <WhiteSpace size="lg"/>
                <Button onClick={this.submitEvt} type="primary">注册</Button>
            </WingBlank>
        )
    }
}
